package org.yankun.exam4j.web.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UrlPathHelper;
import org.yankun.exam4j.security.ip.service.IpService;
import org.yankun.exam4j.session.SessionManager;

public class PermissionInterceptor implements HandlerInterceptor {

	private static final Logger log = Logger.getLogger(PermissionInterceptor.class);
	
	UrlPathHelper urlPathHelper = new UrlPathHelper();
	
	@Resource
	private IpService ipService;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		HttpSession session = request.getSession(false);
		String uriInApplication = urlPathHelper.getPathWithinApplication(request);
		
		String ip = request.getRemoteAddr();
		
		if(ipService.isBlack(ip)){
			response.getWriter().println("您的Ip:"+ip+"无效！");
			log.info("Black try to access");
			return false;
		}
		
		if(!"/login.do".equals(uriInApplication) && !"/login/doLogin.do".equals(uriInApplication)&&
				!"/index.do".equals(uriInApplication)&&!"/".equals(uriInApplication)){
			if(!SessionManager.isLogon(session)){
				response.sendRedirect(request.getContextPath() + "/login.do?state=error");
				return false;
			}
		}
		return true;
	}

}
